﻿/**************************************************************
 *
 * 唯一标识：cafb33e6-0cdf-4bdf-b0dd-84225003e351
 * 命名空间：Xunit.Sgr.Cap.HelperClass
 * 创建时间：2024/7/22 16:33:17
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit.Abstractions;

namespace Xunit.Sgr.Cap.HelperClass
{
    public class TestOutputLogger : ILogger
    {
        private readonly ITestOutputHelper _outputHelper;

        public TestOutputLogger(ITestOutputHelper outputHelper, string categoryName)
        {
            _outputHelper = outputHelper;
            CategoryName = categoryName;
        }

        public string CategoryName { get; }

        public IDisposable? BeginScope<TState>(TState state) where TState : notnull
        {
            return new DisposableAction(state);
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (exception != null)
                _outputHelper.WriteLine($"[{logLevel}] {state} {exception?.Message} {exception?.StackTrace}");
            else
                _outputHelper.WriteLine($"[{logLevel}] {state}");

            //_outputHelper.WriteLine($"[{logLevel}] {formatter.Invoke(state, exception)}");
        }

        private class DisposableAction : IDisposable
        {
            private readonly object _state;

            public DisposableAction(object state)
            {
                _state = state;
            }

            public void Dispose()
            {
            }
        }
    }
}